package com.linkoog.devtools.code_generator.setting.configurable.ui.template;

import com.linkoog.devtools.code_generator.template.model.NodeData;
import com.linkoog.devtools.code_generator.util.ProjectUtils;
import com.intellij.openapi.wm.IdeFocusManager;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import java.awt.*;
import java.util.EventObject;


public class TemplateTreeCellEditor extends DefaultCellEditor {

    private final JTree edit_tree;

    public TemplateTreeCellEditor(@NotNull JTree tree) {
        super(new JTextField());
        edit_tree = tree;
        this.setClickCountToStart(2);
    }

    public boolean isCellEditable(EventObject anEvent) {
        return delegate.isCellEditable(anEvent);
    }

    @Override
    public Component getTreeCellEditorComponent(JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row) {
        final JTextField field = (JTextField)super.getTreeCellEditorComponent(tree, value, isSelected, expanded, leaf, row);

        final Object nodeDataObject = ((DefaultMutableTreeNode)value).getUserObject();
        if (nodeDataObject instanceof NodeData){
            NodeData nodeData = (NodeData) nodeDataObject;
            field.setText(nodeData.getName());
        }

        return field;
    }

    /**
     *  输入entry键，正常结束编辑时，被调用
     */
    public boolean stopCellEditing(){
        doStopEditing();
        return true;
    }

    /**
     *  失去焦点时，非正常结束编辑时，被调用
     */
    public void cancelCellEditing() {
        doStopEditing();
    }

    private void doStopEditing() {
        Object lastSelectedPathComponent = edit_tree.getLastSelectedPathComponent();
        if (lastSelectedPathComponent instanceof DefaultMutableTreeNode){
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) lastSelectedPathComponent;
            final Object nodeDataObject = node.getUserObject();
            if (nodeDataObject instanceof NodeData){
                String new_value = getCellEditorValue().toString();
                NodeData nodeData = (NodeData) nodeDataObject;
                nodeData.setName(new_value);
            }

        }

        requestFocusToTree();
        edit_tree.setEditable(false);
        fireEditingCanceled();
    }

    private void requestFocusToTree() {
        IdeFocusManager.getInstance(ProjectUtils.getCurrentProject()).requestFocus(edit_tree, true);
    }
}
